const knex = require('knex')

let _winConnect = null;

function connect(options = {
    database: 'databsesui', host: '127.0.0.1', user: 'root', password: '123456'
}) {
    const _knexInstance = require('knex')({
        client: 'mysql',
        connection: {
            host: options.host,
            user: options.user,
            password: options.password,
            database: options.database
        },
    });
    _winConnect = _knexInstance;
    return _knexInstance
}

async function add(tableName/*mysql一致*/, params, whereOptions) {
    var queryParams = {}
    if (queryParams.id) {
        queryParams.id = params.id
    } else {
        queryParams={...whereOptions}
    }
    var _one = await getOne(tableName, queryParams)

    if (_one) {
        return _one
    } else {
        await _winConnect(tableName).insert({
            ...params
        })
        return await getOne(tableName, queryParams)
    }
}

async function update(tableName, queryOptions, params) {
    var updateIndex = await _winConnect(tableName).where(queryOptions).update({
        ...params
    })
    if (updateIndex > 0) {
        return getOne(tableName, queryOptions)
    } else {
        return false
    }
}

async function getOne(tableName, params) {
    var oneDemo = await _winConnect(tableName).first("*").where({
        ...params
    })
    return oneDemo;
}

async function getList(tableName, params) {
    var list = await _winConnect(tableName).select("*").where({
        ...params
    }).limit(10).offset(0)
    return list
}

async function getCount(tableName, params) {
    var count = await _winConnect(tableName).count("*").where({
        params
    })
    return count
}


/*
*
* const {
*  connect,
    add,
    update,
    getOne,
    getList,
    getCount,
}=require('../common/db.js')
* */
module.exports = {
    connect,
    add,
    update,
    getOne,
    getList/*自动分页*/,
    getCount,
}